<?php
/**
 * Created by PhpStorm.
 * User: mr.lee
 * Date: 2018/3/3
 * Time: 下午4:48
 */

namespace app\merchant\controller;


use Alipay\Alipayobj;
use app\api\controller\Card;
use app\common\model\Agent;
use app\common\model\CardBonusRule;
use app\common\model\CardCzgive;
use app\common\model\CardLink;
use app\common\model\CardMember;
use app\common\model\CardMemberAli;
use app\common\model\CardQrcode;
use app\common\model\CardRank;
use app\common\model\CardUrlDict;
use app\common\model\CardUserGetAli;
use app\common\model\CardUserUpdateAli;
use app\common\model\Merchant;
use app\common\model\Momerchant;
use think\Controller;
use think\Request;
use think\Session;

class Alicards extends Controller
{

    public function index(){
        $CardMember = new CardMemberAli();
        $template_id = $CardMember->where(['top_mid'=>Session::get('login_top_mid')])->value('template_id');
        if ($template_id){
            $this->redirect('alicards/cardinfoali',array('template_id'=>$template_id));
        }else{
            $this->redirect('alicards/creatcardusali');
        }
    }

    public function opencardlq()
    {
//echo 123;
        $acinfo=$this->getuserinfo(request()->get('auth_code'));

        $params['access_token']=$acinfo['access_token'];
        $params['template_id']=request()->get('template_id');
        $params['request_id']=request()->get('request_id');
        $content = $this->activateform_query($params);
        $params2=$params;
        $params2['uid']=$acinfo['user_id'];
        $params2['infos']=json_decode($content['data']['infos'],true);

        $card=$this->card_open($params2);
        var_dump($card);
        exit();

    }
    public function card_open($param){

        $datas['merchid'] = 501;
        $User = new Merchant();
        $Agent = new Agent();

        $users = $User->where(array('id' => $datas['merchid']))->find();
        $agent = $Agent->where(array('id' => $users['agent']))->find();

        $options = array(

            'appid' => $agent['ali_app_id'], // 填写高级调用功能的app id
            'rsaPrivateKey' => $agent['ali_app_key'],

        );
        $aliObj = new Alipayobj($options);
        $data['app_id'] = $agent['ali_app_id'];
        $data['method'] = "alipay.marketing.card.open";
        $data['charset'] = "UTF-8";
        $data['sign_type'] = "RSA2";
        $data['timestamp'] = date('Y-m-d H:i:s');
        $data['version'] = "1.0";
        $data['auth_token']=$param['access_token'];

        $data['app_auth_token'] = $users['ali_merid'];
        $data['biz_content'] = json_encode(array(
            'out_serial_no' => date('YmdHis').rand(10000,99999),
            'card_template_id'=>$param['template_id'],
            'card_user_info'=>array(
                'user_uni_id'=>$param['uid'],
                'user_uni_id_type'=>"UID",
            ),
            'card_ext_info'=>array(
                'external_card_no'=>date('Ymdhis').rand(1000,9999),
              'open_date'=>date('Y-m-d H:i:s'),
              'valid_date'=>"2020-12-12 23:59:59",
            ),
//            'member_ext_info'=>array(
//                'name'=>$param['infos'][1]['OPEN_FORM_FIELD_NAME'],
//                'cell'=>$param['infos'][0]['OPEN_FORM_FIELD_MOBILE'],
//            ),

        ));
        $signContent = $aliObj->rsaSign($data, $signType = "RSA2");
        $data['sign'] = $signContent;
//return $data;
        $sj = $aliObj->scanpay($data);
        $content = json_decode(iconv("GB2312", "UTF-8//IGNORE", $sj), true);
        return $content;
    }

    //查询用户提交的会员卡表单信息
    public function activateform_query($param)
    {
        $datas['merchid'] = 501;
        $User = new Merchant();
        $Agent = new Agent();
        $users = $User->where(array('id' => $datas['merchid']))->find();
        $agent = $Agent->where(array('id' => $users['agent']))->find();
        $options = array(
            'appid' => $agent['ali_app_id'], // 填写高级调用功能的app id
            'rsaPrivateKey' => $agent['ali_app_key'],
        );
        $aliObj = new Alipayobj($options);
        $data['app_id'] = $agent['ali_app_id'];
        $data['method'] = "alipay.marketing.card.activateform.query";
        $data['charset'] = "UTF-8";
        $data['sign_type'] = "RSA2";
        $data['timestamp'] = date('Y-m-d H:i:s');
        $data['version'] = "1.0";
        $data['auth_token']=$param['access_token'];
        $data['app_auth_token'] = $users['ali_merid'];
        $data['biz_content'] = json_encode(array(
            'biz_type' => "MEMBER_CARD",
            'template_id' => $param['template_id'],
            "request_id" => $param['request_id'],
        ));
        $signContent = $aliObj->rsaSign($data, $signType = "RSA2");
        $data['sign'] = $signContent;
        $sj = $aliObj->scanpay($data);
        $content = json_decode(iconv("GB2312", "UTF-8//IGNORE", $sj), true);
        if($content['alipay_marketing_card_activateform_query_response']['code']==10000){
            $info['code']=0;
            $info['data']['infos']=$content['alipay_marketing_card_activateform_query_response']['infos'];
        }else{
            $info['code']=$content['alipay_marketing_card_activateform_query_response']['code'];
            $info['message']=$content['alipay_marketing_card_activateform_query_response']['msg'];
        }
        return $info;
    }
    //获取用户userid
    public function getuserinfo($code="e2691129a3424fa696921ac1a56fRX10"){
        $datas['merchid'] = 501;
        $User = new Merchant();
        $Agent = new Agent();
        $users = $User->where(array('id' => $datas['merchid']))->find();
        $agent = $Agent->where(array('id' => $users['agent']))->find();
        $options = array(
            'appid' => $agent['ali_app_id'], // 填写高级调用功能的app id
            'rsaPrivateKey' => $agent['ali_app_key'],
        );
        $aliObj = new Alipayobj($options);
        $data['app_id'] = $agent['ali_app_id'];
        $data['method'] = "alipay.system.oauth.token";
        $data['charset'] = "UTF-8";
        $data['sign_type'] = "RSA2";
        $data['timestamp'] = date('Y-m-d H:i:s');
        $data['version'] = "1.0";
        $data['app_auth_token'] = $users['ali_merid'];
        $data['grant_type'] = 'authorization_code';
        $data['code'] = $code;
        $signContent = $aliObj->rsaSign($data, $signType = "RSA2");
        $data['sign'] = $signContent;
        $uid = $aliObj->getuid($data);
        $user = json_decode($uid, true);
        $params['user_id']=$user['alipay_system_oauth_token_response']['user_id'];
        $params['access_token']=$user['alipay_system_oauth_token_response']['access_token'];
        return $params;

    }


    //会员卡列表
    public function carduslistali(){
        //搜索条件
        $request = request();
        $arrp = $request->get();
        unset($arrp['page']);
        $map = [];
        if ($arrp) {
            $map['title'] = ['like', '%' . trim($arrp['key']) . '%'];
        } else {
            $arrp['title'] = '';
        }
        $CardMemberAli = new CardMemberAli();
//        $mid = $this->get_mer_mid();
//        //未创建子门店则获取top_mid
//        if ($mid !== '') {
//            $map['mid'] = ['in', $mid];
//        }else{
            $map['top_mid'] = Session::get('login_top_mid');
//        }
        $list = $CardMemberAli->where($map)->paginate(10,false, ['key' => request()->param()]);
        $mab['card_type'] = 'OUT_MEMBER_CARD';
        $mab['top_mid'] = Session::get('login_top_mid');
        $only = $CardMemberAli->where($mab)->find();
        if ($only){
            $card['only'] = 1;
        }else{
            $card['only'] = 0;
        }
        $this->assign('card',$card);
        $this->assign('list',$list);
        return $this->fetch();
    }

    //会员卡信息
    public function cardinfoali(){
        $arr = request()->param();
        if ($arr['template_id']){
            $CardMemberAli = new CardMemberAli();
            $info = $CardMemberAli->where(['template_id'=>$arr['template_id']])->find();
            if ($info){
                $this->assign('info',$info);
                return $this->fetch();
            }else{
                die("<script>alert('该会员卡状态异常')</script>");
                $this->redirect('alicards/carduslistali');
            }
        }
    }

    //创建会员卡
    public function creatcardusali($mid)
    {
        $CardMemberAli = new CardMemberAli();
        if (Request()->isPost()) {
            $datas['merchid'] = $mid;
            $arr = request()->post();
//            return json($arr);
            $User = new Merchant();
            $Agent = new Agent();
            $users = $User->where(array('id' => $mid))->find();
            $agent = $Agent->where(array('id' => $users['agent']))->find();
            $options = array(
                'appid' => $agent['ali_app_id'], // 填写高级调用功能的app id
                'rsaPrivateKey' => $agent['ali_app_key'],
            );
            $aliObj = new Alipayobj($options);
            //通过top_mid 获取微信会员卡信息
            //卡片信息
            $template_style_info = array(
                "card_show_name" => $arr['style']['card_show_name'],
                "logo_id" => $arr['style']['logo_url_id'],//logo图片
                "background_id" => $arr['style']['bg_url_id'],//背景图片
                "bg_color" => "rgb(55,112,179)",//背景色（rgb）
            );
            //权益信息
            $template_benefit_info = array(
                "title" => "会员权益",//权益描述
                "benefit_desc" => $arr['benfit']['desc'],//权益描述信息
                "start_date" => "2016-07-18 15:17:23",//开始时间
                "end_date" => "2020-07-18 15:17:23",//权益结束时间
            );
            $field_rule_list = array(
                array(
                    'field_name' => 'Balance',
                    'rule_name' => 'ASSIGN_FROM_REQUEST',
                    'rule_value' => 'Balance'
                ),
                array(
                    'field_name' => 'Point',
                    'rule_name' => 'ASSIGN_FROM_REQUEST',
                    'rule_value' => 'Point'
                ),
                array(
                    'field_name' => 'Level',
                    'rule_name' => 'ASSIGN_FROM_REQUEST',
                    'rule_value' => 'Level'
                ),
            );

            if ($arr['is_cell1'] == 1){
                var_dump('222654a56s4d6545as64d65as');
                $column_info_list = array(
                    array(
                        'code'=>'POINT',
                        'operate_type'=>'staticinfo',
                        'title'=>'积分',
                    ),
                    array(
                        'code'=>'BALANCE',
                        'operate_type'=>'staticinfo',
                        'title'=>'余额',
                    ),
                    array(
                        'code'=>'LEVEL',
                        'operate_type'=>'staticinfo',
                        'title'=>'等级',
                    ),
                    array(
                        'code'=>$arr['column1']['code'],
                        'operate_type'=>'openWeb',
                        'title'=>$arr['column1']['title'],
                        'more_info'=>array(
                            'url'=>$arr['column1']['url'].'/mid/'.$mid,
//                            'params'=>json_encode(
//                                array('mid'=>$mid)
//                            )
                        )
                    ),
                );
            }elseif($arr['is_cell1'] == 1 && $arr['is_cell2'] == 1){
                var_dump('111654a56s4d6545as64d65as');
                $column_info_list = array(
                    array(
                        'code'=>'POINT',
                        'operate_type'=>'staticinfo',
                        'title'=>'积分',
                    ),
                    array(
                        'code'=>'BALANCE',
                        'operate_type'=>'staticinfo',
                        'title'=>'余额',
                    ),
                    array(
                        'code'=>'LEVEL',
                        'operate_type'=>'staticinfo',
                        'title'=>'等级',
                    ),
                    array(
                        'code'=>$arr['column1']['code'],
                        'operate_type'=>'openWeb',
                        'title'=>$arr['column1']['title'],
                        'more_info'=>array(
                            'url'=>$arr['column1']['url'].'/mid/'.$mid,
//                            'params'=>json_encode(
//                                array('mid'=>$mid)
//                            )
                        )
                    ),
                    array(
                        'code'=>$arr['column2']['code'],
                        'operate_type'=>'openWeb',
                        'title'=>$arr['column2']['title'],
                        'more_info'=>array(
                            'url'=>$arr['column2']['url'].'/mid/'.$mid,
//                            'params'=>json_encode(
//                                array('mid'=>$mid)
//                            )
                        )
                    ),
                );
            }elseif($arr['is_cell1'] == 1 && $arr['is_cell2'] == 1 && $arr['is_cell3'] == 1){
                $column_info_list = array(
                    array(
                        'code'=>'POINT',
                        'operate_type'=>'staticinfo',
                        'title'=>'积分',
                    ),
                    array(
                        'code'=>'BALANCE',
                        'operate_type'=>'staticinfo',
                        'title'=>'余额',
                    ),
                    array(
                        'code'=>'LEVEL',
                        'operate_type'=>'staticinfo',
                        'title'=>'等级',
                    ),
                    array(
                        'code'=>$arr['column1']['code'],
                        'operate_type'=>'openWeb',
                        'title'=>$arr['column1']['title'],
                        'more_info'=>array(
                            'url'=>$arr['column1']['url'].'/mid/'.$mid,
//                            'params'=>json_encode(
//                                array('mid'=>$mid)
//                            )
                        )
                    ),
                    array(
                        'code'=>$arr['column2']['code'],
                        'operate_type'=>'openWeb',
                        'title'=>$arr['column2']['title'],
                        'more_info'=>array(
                            'url'=>$arr['column2']['url'].'/mid/'.$mid,
//                            'params'=>json_encode(
//                                array('mid'=>$mid)
//                            )
                        )
                    ),
                    array(
                        'code'=>$arr['column3']['code'],
                        'operate_type'=>'openWeb',
                        'title'=>$arr['column3']['title'],
                        'more_info'=>array(
                            'url'=>$arr['column3']['url'].'/mid/'.$mid,
//                            'params'=>json_encode(
//                                array('mid'=>$mid)
//                            )
                        )
                    ),
                );
            }else{
                $column_info_list = array();
            }

            //接口传递参数
            $data['app_id'] = $agent['ali_app_id'];
            $data['method'] = "alipay.marketing.card.template.create";
            $data['charset'] = "UTF-8";
            $data['sign_type'] = "RSA2";
            $data['timestamp'] = date('Y-m-d H:i:s');
            $data['version'] = "1.0";
            $data['notify_url'] = 'https://'.$agent['open_url'];
            $data['app_auth_token'] = $users['ali_merid'];
            //biz_content
            $biz_content['request_id'] =  date("YmdHis") . rand(1000, 9999);
            $biz_content['card_type'] = "OUT_MEMBER_CARD";
            $biz_content['biz_no_suffix_len'] = 12;
            $biz_content['write_off_type'] = "qrcode";
            $biz_content['template_style_info'] = $template_style_info;
            $biz_content['field_rule_list'] = $field_rule_list;
            if ($arr['is_cell1'] == 1 || $arr['is_cell2'] == 1 || $arr['is_cell3'] == 1){
                $biz_content['column_info_list'] = $column_info_list;
            }
            $data['biz_content'] = json_encode($biz_content);

            $signContent = $aliObj->rsaSign($data, $signType = "RSA2");
            $data['sign'] = $signContent;
            //接口传参

            $sj = $aliObj->scanpay($data);
            $content = json_decode(iconv("GB2312", "UTF-8//IGNORE", $sj), true);

            //结果判断
            if ($content['alipay_marketing_card_template_create_response']['code'] == 10000) {
                $template_id = $content['alipay_marketing_card_template_create_response']['template_id'];
                $merchant = new Merchant();
                $datas['template_id'] = $template_id;
                $datas['top_mid'] = $merchant->where(['id' => $mid])->value('top_mid');
                $datas['mid'] = $mid;
                $datas['card_type'] = 'OUT_MEMBER_CARD';
                $datas['card_show_name'] = $arr['style']['card_show_name'];
                $datas['bg_color'] = $arr['style']['bg_color'];
                $datas['logo_url_id'] = $arr['style']['logo_url_id'];
                $datas['logo_url_abs'] = $arr['style']['logo_url_abs'];
                $datas['logo_url_ali'] = $arr['style']['logo_url_ali'];
                $datas['bg_url_id'] = $arr['style']['bg_url_id'];
                $datas['bg_url_abs'] = $arr['style']['bg_url_abs'];
                $datas['bg_url_ali'] = $arr['style']['bg_url_ali'];
                $datas['is_cell1'] = $arr['is_cell1'];
                $datas['column1'] = json_encode($arr['column1'],JSON_UNESCAPED_UNICODE);
                $datas['is_cell2'] = $arr['is_cell2'];
                $datas['column2'] = json_encode($arr['column2'],JSON_UNESCAPED_UNICODE);
                $datas['is_cell3'] = $arr['is_cell3'];
                $datas['column3'] = json_encode($arr['column3'],JSON_UNESCAPED_UNICODE);
                $datas['biz_content'] = json_encode($data['biz_content'], JSON_UNESCAPED_UNICODE);
                $datas['template_style_info'] = json_encode($template_style_info, JSON_UNESCAPED_UNICODE);
                $datas['template_benefit_info'] = json_encode($template_benefit_info, JSON_UNESCAPED_UNICODE);
                $datas['field_rule_list'] = json_encode($field_rule_list, JSON_UNESCAPED_UNICODE);
                $datas['column_info_list'] = json_encode($column_info_list,JSON_UNESCAPED_UNICODE);

                $datas['create_time'] = time();
                $res = $CardMemberAli->save($datas);
                if ($res) {
                    $params['code'] = 0;
                    $params['data']['template_id'] = $template_id;
                } else {
                    $params['code'] = 2;
                    $params['data']['template_id'] = $template_id . '数据存储错误！';
                }
            } else {
                $params['code'] = $content['alipay_marketing_card_template_create_response']['code'];
                $params['data']['msg'] = $content['alipay_marketing_card_template_create_response']['msg'];;
            }
            return json($params);
        }else{
            $top_mid = Session::get('login_top_mid');
            $card = $CardMemberAli->where(array('top_mid' => $top_mid))->find();
            $CardMember = new CardMember();
            $cardus = $CardMember->where(array('top_mid' => $top_mid))->find();
            $CardUrlDict = new CardUrlDict();
            $Momerchant = new Momerchant();
            $dict['card_type'] = 'OUT_MEMBER_CARD';
            $dict['type'] = 1;
            $dict['statu'] = 0;
            $urllist = $CardUrlDict->where($dict)->select();
            $card['mid'] = $mid;
            $moinfo = $Momerchant->where(['id'=>Session::get('login_top_mid')])->field('img,img_abs,merchant_name,tel,cust_call')->find();
            $this->assign('moinfo',$moinfo);
            $this->assign('card',$card);
            $this->assign('cardus',$cardus);
            $this->assign('urllists',[]);
            $this->assign('urllist',$urllist);
            return $this->fetch();
        }

    }


    //会员卡修改
    public function editcardsali($template_id){
        $CardMemberAli = new CardMemberAli();
        $info = $CardMemberAli->where('template_id',$template_id)->find();
        if (Request()->isPost()){
            $datas['merchid'] = $info['mid'];
            $arr = request()->post();

            $User = new Merchant();
            $Agent = new Agent();
            $users = $User->where(array('id' => $info['mid']))->find();
            $agent = $Agent->where(array('id' => $users['agent']))->find();
            $options = array(
                'appid' => $agent['ali_app_id'], // 填写高级调用功能的app id
                'rsaPrivateKey' => $agent['ali_app_key'],
            );
            $aliObj = new Alipayobj($options);
            //通过top_mid 获取微信会员卡信息
            //卡片信息
            $template_style_info = array(
                "card_show_name" => $arr['style']['card_show_name'],
                "logo_id" => $arr['style']['logo_url_id'],//logo图片
                "background_id" => $arr['style']['bg_url_id'],//背景图片
                "bg_color" => "rgb(55,112,179)",//背景色（rgb）
            );
            //权益信息
            $template_benefit_info = array(
                "title" => "会员权益",//权益描述
                "benefit_desc" => $arr['benfit']['desc'],//权益描述信息
                "start_date" => "2016-07-18 15:17:23",//开始时间
                "end_date" => "2020-07-18 15:17:23",//权益结束时间
            );
            $field_rule_list = array(
                array(
                    'field_name' => 'Balance',
                    'rule_name' => 'ASSIGN_FROM_REQUEST',
                    'rule_value' => 'Balance'
                ),
                array(
                    'field_name' => 'Point',
                    'rule_name' => 'ASSIGN_FROM_REQUEST',
                    'rule_value' => 'Point'
                ),
            array(
                'field_name' => 'Level',
                'rule_name' => 'ASSIGN_FROM_REQUEST',
                'rule_value' => 'Level'
            ),
            );
            //栏位信息
            if ($arr['is_cell1'] == 1){
                $column_info_list = array(
                    array(
                        'code'=>$arr['column1']['code'],
                        'operate_type'=>'openWeb',
                        'title'=>$arr['column1']['title'],
                        'more_info'=>array(
                            'url'=>$arr['column1']['url'],
//                            'params'=>json_encode(
//                                array('mid'=>$info['mid'])
//                            )
                        )
                    ),
                );
            }elseif($arr['is_cell1'] == 1 && $arr['is_cell2'] == 1){
                $column_info_list = array(
                    array(
                        'code'=>$arr['column1']['code'],
                        'operate_type'=>'openWeb',
                        'title'=>$arr['column1']['title'],
                        'more_info'=>array(
                            'url'=>$arr['column1']['url'],
//                            'params'=>json_encode(
//                                array('mid'=>$info['mid'])
//                            )
                        )
                    ),
                    array(
                        'code'=>$arr['column2']['code'],
                        'operate_type'=>'openWeb',
                        'title'=>$arr['column2']['title'],
                        'more_info'=>array(
                            'url'=>$arr['column2']['url'],
//                            'params'=>json_encode(
//                                array('mid'=>$info['mid'])
//                            )
                        )
                    ),
                );
            }elseif($arr['is_cell1'] == 1 && $arr['is_cell2'] == 1 && $arr['is_cell3'] == 1){
                $column_info_list = array(
                    array(
                        'code'=>$arr['column1']['code'],
                        'operate_type'=>'openWeb',
                        'title'=>$arr['column1']['title'],
                        'more_info'=>array(
                            'url'=>$arr['column1']['url'],
//                            'params'=>json_encode(
//                                  array('mid'=>$info['mid'])
//                            )
                        )
                    ),
                    array(
                        'code'=>$arr['column2']['code'],
                        'operate_type'=>'openWeb',
                        'title'=>$arr['column2']['title'],
                        'more_info'=>array(
                            'url'=>$arr['column2']['url'],
//                            'params'=>json_encode(
//                                  array('mid'=>$info['mid'])
//                            )
                        )
                    ),
                    array(
                        'code'=>$arr['column3']['code'],
                        'operate_type'=>'openWeb',
                        'title'=>$arr['column3']['title'],
                        'more_info'=>array(
                            'url'=>$arr['column3']['url'],
//                            'params'=>json_encode(
//                                  array('mid'=>$info['mid'])
//                            )
                        )
                    ),
                );
            }

            //接口传递参数
            $data['app_id'] = $agent['ali_app_id'];
            $data['method'] = "alipay.marketing.card.template.modify";
            $data['charset'] = "UTF-8";
            $data['sign_type'] = "RSA2";
            $data['timestamp'] = date('Y-m-d H:i:s');
            $data['version'] = "1.0";
//            $data['notify_url'] = 'https://os.wunengkeji.com/';
            $data['app_auth_token'] = $users['ali_merid'];
            //biz_content
            $biz_content['request_id'] =  date("YmdHis") . rand(1000, 9999);
            $biz_content['template_id'] = $info['template_id'];
            $biz_content['card_type'] = "OUT_MEMBER_CARD";
            $biz_content['write_off_type'] = "qrcode";
            $biz_content['template_style_info'] = $template_style_info;
            $biz_content['field_rule_list'] = $field_rule_list;
            if ($arr['is_cell1'] == 1 || $arr['is_cell2'] == 1 || $arr['is_cell3'] == 1){
                $biz_content['column_info_list'] = $column_info_list;
            }
            $data['biz_content'] = json_encode($biz_content);
            $signContent = $aliObj->rsaSign($data, $signType = "RSA2");
            $data['sign'] = $signContent;
            //接口传参
            var_dump(json_encode($arr,JSON_UNESCAPED_UNICODE));
            var_dump(json_encode($biz_content,JSON_UNESCAPED_UNICODE));
//            return json($data);
//            exit();
            $sj = $aliObj->scanpay($data);
            $content = json_decode(iconv("GB2312", "UTF-8//IGNORE", $sj), true);

            //结果判断
            if ($content['alipay_marketing_card_template_modify_response']['code'] == 10000) {
                $template_id = $content['alipay_marketing_card_template_modify_response']['template_id'];
                $merchant = new Merchant();

                $datas['card_show_name'] = $arr['style']['card_show_name'];
                $datas['bg_color'] = $arr['style']['bg_color'];
                $datas['logo_url_id'] = $arr['style']['logo_url_id'];
                $datas['logo_url_abs'] = $arr['style']['logo_url_abs'];
                $datas['logo_url_ali'] = $arr['style']['logo_url_ali'];
                $datas['bg_url_id'] = $arr['style']['bg_url_id'];
                $datas['bg_url_abs'] = $arr['style']['bg_url_abs'];
                $datas['bg_url_ali'] = $arr['style']['bg_url_ali'];
                $datas['is_cell1'] = $arr['is_cell1'];
                $datas['column1'] = json_encode($arr['column1'],JSON_UNESCAPED_UNICODE);
                $datas['is_cell2'] = $arr['is_cell2'];
                $datas['column2'] = json_encode($arr['column2'],JSON_UNESCAPED_UNICODE);
                $datas['is_cell3'] = $arr['is_cell3'];
                $datas['column3'] = json_encode($arr['column3'],JSON_UNESCAPED_UNICODE);
                $datas['biz_content'] = json_encode($data['biz_content'], JSON_UNESCAPED_UNICODE);
                $datas['template_style_info'] = json_encode($template_style_info, JSON_UNESCAPED_UNICODE);
                $datas['template_benefit_info'] = json_encode($template_benefit_info, JSON_UNESCAPED_UNICODE);
                $datas['field_rule_list'] = json_encode($field_rule_list, JSON_UNESCAPED_UNICODE);
//                $datas['column_info_list'] = json_encode($column_info_list,JSON_UNESCAPED_UNICODE);

                $datas['create_time'] = time();
                $datasup['template_id'] = $template_id;
                $res = $CardMemberAli->save($datas,$datasup);
//                return json($res);
                if ($res) {
                    $params['code'] = 0;
                    $params['data']['template_id'] = $template_id;
                } else {
                    $params['code'] = 2;
                    $params['data']['template_id'] = $template_id . '数据存储错误！';
                }
            } else {
                $params['code'] = $content['alipay_marketing_card_template_modify_response']['code'];
                $params['data']['msg'] = $content['alipay_marketing_card_template_modify_response']['msg'];;
            }
            return json($params);
        }else{
            $CardUrlDict = new CardUrlDict();
            $dict['card_type'] = 'OUT_MEMBER_CARD';
            $dict['type'] = 1;
            $dict['statu'] = 0;
            $urllist = $CardUrlDict->where($dict)->select();
            $info['column1'] = json_decode($info['column1'],true);
            $info['column2'] = json_decode($info['column2'],true);
            $info['column3'] = json_decode($info['column3'],true);
            $this->assign('urllists',[]);
            $this->assign('urllist',$urllist);
            $this->assign('card',$info);
            return $this->fetch();
        }
    }

    //会员卡详情
    public function getcardusinfoali(){
        if (Request()->isAjax()){
            $arr = request()->post();
            $CardMemberAli = new CardMemberAli();
            $map['id'] = $arr['id'];
            $map['top_mid'] = Session::get('login_top_mid');
            $info = $CardMemberAli->where($map)->find();
            return json($info);
        }
    }

    //领取会员详情
    public function getcardinfoali(){
        if (Request()->isAjax()){
            $arr = request()->post();
            $CardUserGet = new CardUserGetAli();
            $map['id'] = $arr['id'];
            $user = $CardUserGet->where($map)->find();
            return json($user);
        }
    }

    //更新
    public function updatecardsali(){
//        if (Request()->isAjax()) {

            $arr = request()->param();
            $CardGetUserAli = new CardUserGetAli();
            $user = $CardGetUserAli->where(['id'=>$arr['id'],'top_mid'=>Session::get('login_top_mid')])->find();
            //初始化
            $datas['merchid'] = $user['mid'];
            $User = new Merchant();
            $Agent = new Agent();
            $users = $User->where(array('id' => $datas['merchid']))->find();
            $agent = $Agent->where(array('id' => $users['agent']))->find();
            $options = array(
                'appid' => $agent['ali_app_id'], // 填写高级调用功能的app id
                'rsaPrivateKey' => $agent['ali_app_key'],
            );
            $aliObj = new Alipayobj($options);
            $data['app_id'] = $agent['ali_app_id'];
            $data['method'] = "alipay.marketing.card.update";
            $data['charset'] = "UTF-8";
            $data['sign_type'] = "RSA2";
            $data['timestamp'] = date('Y-m-d H:i:s');
            $data['version'] = "1.0";
            $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
            $data['app_auth_token'] = $users['ali_merid'];
            $data['biz_content'] = json_encode(array(
                'target_card_no' => $user['code'],
                'target_card_no_type' => 'BIZ_CARD',
                'occur_time'=>date('Y-m-d H:i:s'),
                'card_info'=>array(
                    'open_date'=>$user['open_date'],
                    'valid_date'=>$user['valid_date'],
                    'point'=>300,
                    'balance'=>300
                ),
                'notify_messages'=>array(
                    array(
                        'message_type'=>'POINT_UPDATE',
                        'ext_info'=>'积分变动300',
                    ),
                    array(
                        'message_type'=>'BALANCE_UPDATE',
                        'ext_info'=>'余额变动300',
                    ),
                ),
            ));
            $signContent = $aliObj->rsaSign($data, $signType = "RSA2");
            $data['sign'] = $signContent;
            $sj = $aliObj->scanpay($data);
            $content = json_decode(iconv("GB2312", "UTF-8//IGNORE", $sj), true);
            return json($content);
//        }
    }

    //充值积分
    public function inc_bonusali(){
        if (Request()->isAjax()) {
            $arr = request()->param();

            $CardGetUserAli = new CardUserGetAli();

            $res = $CardGetUserAli->where(['id' => $arr['id'], 'top_mid' => Session::get('login_top_mid')])->setInc('bonus', $arr['add_bonus']);
            if ($res) {
                $user = $CardGetUserAli->where(['id' => $arr['id'], 'top_mid' => Session::get('login_top_mid')])->field('template_id,user_id,mid,code,bonus,balance,open_date,valid_date')->find();

                //初始化
                $datas['merchid'] = $user['mid'];
                $User = new Merchant();
                $Agent = new Agent();
                $users = $User->where(array('id' => $datas['merchid']))->find();
                $agent = $Agent->where(array('id' => $users['agent']))->find();
                $options = array(
                    'appid' => $agent['ali_app_id'], // 填写高级调用功能的app id
                    'rsaPrivateKey' => $agent['ali_app_key'],
                );
                $aliObj = new Alipayobj($options);
                $data['app_id'] = $agent['ali_app_id'];
                $data['method'] = "alipay.marketing.card.update";
                $data['charset'] = "UTF-8";
                $data['sign_type'] = "RSA2";
                $data['timestamp'] = date('Y-m-d H:i:s');
                $data['version'] = "1.0";
                $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
                $data['app_auth_token'] = $users['ali_merid'];
                $data['biz_content'] = json_encode(array(
                    'target_card_no' => $user['code'],
                    'target_card_no_type' => 'BIZ_CARD',
                    'occur_time' => date('Y-m-d H:i:s'),
                    'card_info' => array(
                        'open_date' => $user['open_date'],
                        'valid_date' => $user['valid_date'],
                        'point' => $user['bonus'],
                    ),
                    'notify_messages' => array(
                        array(
                            'message_type' => 'POINT_UPDATE',
                            'ext_info' => '积分变动'.$arr['add_bonus'],
                        ),
                    ),
                ));
                $signContent = $aliObj->rsaSign($data, $signType = "RSA2");
                $data['sign'] = $signContent;
                $sj = $aliObj->scanpay($data);
                $content = json_decode(iconv("GB2312", "UTF-8//IGNORE", $sj), true);
                if ($content['alipay_marketing_card_update_response']['code'] = 10000) {
                    //记录
                    $CardUpdateAli = new CardUserUpdateAli();
                    $datas['top_mid']=Session::get('login_top_mid');
                    $datas['mid']=$user['mid'];
                    $datas['user_id']=$user['user_id'];
                    $datas['code']=$user['code'];
                    $datas['con_username']= $arr['username'];
                    $datas['template_id']=$user['template_id'];
                    $datas['add_bonus']=$arr['add_bonus'];
                    $datas['record_bonus']=$arr['record_balance'];
                    $datas['hx_fs']=4;
                    $datas['source']=1;
                    $datas['create_time']=time();
                    $datas['reason']=3;
                    $datas['type'] = $arr['type'];
                    $datas['notify_optional'] = json_encode($content,JSON_UNESCAPED_UNICODE);
                    $CardUpdateAli->allowField(true)->save($datas);
                    $arrs = ['code'=>0,'message'=>'成功'];
                }else{
                    $arrs = ['code'=>$content['alipay_marketing_card_update_response']['code'],'message'=>$content['alipay_marketing_card_update_response']['msg']];
                }
            }else{
                $arrs = ['code'=>9001,'message'=>'更新失败'];
            }
        }else{
            $arrs = ['code'=>9002,'message'=>'访问方式不正确'];
        }
        return json($arrs);
    }

    //核销积分
    public function hx_bonusali(){
        if (Request()->isAjax()) {
            $arr = request()->param();
//            return json($arr);
            $CardGetUserAli = new CardUserGetAli();

            $res = $CardGetUserAli->where(['id' => $arr['id']])->setDec('bonus', $arr['bonus']);
            if ($res) {
//
                $user = $CardGetUserAli->where(['id' => $arr['id'], 'top_mid' => Session::get('login_top_mid')])->field('template_id,user_id,mid,code,bonus,balance,open_date,valid_date')->find();
                //初始化
                $datas['merchid'] = $user['mid'];
                $User = new Merchant();
                $Agent = new Agent();
                $users = $User->where(array('id' => $datas['merchid']))->find();
                $agent = $Agent->where(array('id' => $users['agent']))->find();
                $options = array(
                    'appid' => $agent['ali_app_id'], // 填写高级调用功能的app id
                    'rsaPrivateKey' => $agent['ali_app_key'],
                );
                $aliObj = new Alipayobj($options);
                $data['app_id'] = $agent['ali_app_id'];
                $data['method'] = "alipay.marketing.card.update";
                $data['charset'] = "UTF-8";
                $data['sign_type'] = "RSA2";
                $data['timestamp'] = date('Y-m-d H:i:s');
                $data['version'] = "1.0";
                $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
                $data['app_auth_token'] = $users['ali_merid'];
                $data['biz_content'] = json_encode(array(
                    'target_card_no' => $user['code'],
                    'target_card_no_type' => 'BIZ_CARD',
                    'occur_time' => date('Y-m-d H:i:s'),
                    'card_info' => array(
                        'open_date' => $user['open_date'],
                        'valid_date' => $user['valid_date'],
                        'point' => abs($user['bonus']),
                    ),
                    'notify_messages' => array(
                        array(
                            'message_type' => 'POINT_UPDATE',
                            'ext_info' => '积分变动'.$arr['bonus'],
                        ),
                    ),
                ));
//                return json($data);
                $signContent = $aliObj->rsaSign($data, $signType = "RSA2");
                $data['sign'] = $signContent;
                $sj = $aliObj->scanpay($data);
                $content = json_decode(iconv("GB2312", "UTF-8//IGNORE", $sj), true);
                if ($content['alipay_marketing_card_update_response']['code'] = 10000) {
                    //记录
                    $CardUpdateAli = new CardUserUpdateAli();
                    $datas['top_mid'] = Session::get('login_top_mid');
                    $datas['mid'] = $user['mid'];
                    $datas['user_id'] = $user['user_id'];
                    $datas['code']=$user['code'];
                    $datas['con_username'] = $arr['username'];
                    $datas['template_id'] = $user['template_id'];
                    $datas['del_bonus'] = $arr['bonus'];
                    $datas['record_bonus'] = '积分核销';
                    $datas['hx_fs'] = 4;
                    $datas['source'] = 1;
                    $datas['create_time'] = time();
                    $datas['reason'] = 3;
                    $datas['type'] = $arr['type'];
                    $datas['notify_optional'] = json_encode($content, JSON_UNESCAPED_UNICODE);
                    $CardUpdateAli->allowField(true)->save($datas);
                    $arrs = ['code'=>0,'message'=>'成功'];
                }else{
                    $arrs = ['code'=>$content['alipay_marketing_card_update_response']['code'],'message'=>$content['alipay_marketing_card_update_response']['msg']];
                }
            }else{
                $arrs = ['code'=>9001,'message'=>'更新失败'];
            }
        }else{
            $arrs = ['code'=>9002,'message'=>'访问方式不正确'];
        }
        return json($arrs);
    }

    //充值余额
    public function getrechargeali()
    {
        if (Request()->isAjax()) {
            $arr = request()->param();
//            return json($arr);
            $CardGetUserAli = new CardUserGetAli();
//            return json(Session::get('login_top_mid'));
            //余额更新
            if ($arr['giveid'] == '') {
                $arrc['add_balance'] = $arr['add_balance'];
            } else {
                //赠送金额
                $CardZsgive = new CardCzgive();
                $zsgive = $CardZsgive->where('id', $arr['giveid'])->find();
                $arrc['add_balance'] = $zsgive['cz_money'] + $zsgive['zs_money'];
            }

            $res = $CardGetUserAli->where(['id' => $arr['id'], 'top_mid' => Session::get('login_top_mid')])->setInc('balance', $arrc['add_balance']);
            if ($res) {
                $user = $CardGetUserAli->where(['id' => $arr['id'], 'top_mid' => Session::get('login_top_mid')])->field('template_id,user_id,mid,code,bonus,balance,open_date,valid_date')->find();

                //初始化
                $datas['merchid'] = $user['mid'];
                $User = new Merchant();
                $Agent = new Agent();
                $users = $User->where(array('id' => $datas['merchid']))->find();
                $agent = $Agent->where(array('id' => $users['agent']))->find();
                $options = array(
                    'appid' => $agent['ali_app_id'], // 填写高级调用功能的app id
                    'rsaPrivateKey' => $agent['ali_app_key'],
                );
                $aliObj = new Alipayobj($options);
                $data['app_id'] = $agent['ali_app_id'];
                $data['method'] = "alipay.marketing.card.update";
                $data['charset'] = "UTF-8";
                $data['sign_type'] = "RSA2";
                $data['timestamp'] = date('Y-m-d H:i:s');
                $data['version'] = "1.0";
                $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
                $data['app_auth_token'] = $users['ali_merid'];
                $data['biz_content'] = json_encode(array(
                    'target_card_no' => $user['code'],
                    'target_card_no_type' => 'BIZ_CARD',
                    'occur_time' => date('Y-m-d H:i:s'),
                    'card_info' => array(
                        'open_date' => $user['open_date'],
                        'valid_date' => $user['valid_date'],
                        'balance' => $user['balance'],
                    ),
                    'notify_messages' => array(
                        array(
                            'message_type' => 'BALANCE_UPDATE',
                            'ext_info' => '余额变动300' . $arr['add_balance'],
                        ),
                    ),
                ));
                $signContent = $aliObj->rsaSign($data, $signType = "RSA2");

                $data['sign'] = $signContent;
                $sj = $aliObj->scanpay($data);
                $content = json_decode(iconv("GB2312", "UTF-8//IGNORE", $sj), true);

                if ($content['alipay_marketing_card_update_response']['code'] = 10000) {
                    //记录

                    $CardUpdateAli = new CardUserUpdateAli();
                    $datas['top_mid'] = Session::get('login_top_mid');
                    $datas['mid'] = $user['mid'];
                    $datas['user_id'] = $user['user_id'];
                    $datas['code']=$user['code'];
                    $datas['con_username'] = $arr['username'];
                    $datas['template_id'] = $user['template_id'];
                    $datas['add_balance'] = $arr['add_balance'];
                    $datas['record_balance'] = '余额充值';
                    $datas['hx_fs'] = 4;
                    $datas['source'] = 1;
                    $datas['create_time'] = time();
                    $datas['reason'] = 3;
                    $datas['type'] = $arr['type'];
                    $datas['notify_optional'] = json_encode($content, JSON_UNESCAPED_UNICODE);
                    if ($arr['giveid'] == '') {
                        $datas['pay_balance'] = $datas['add_balance'];
                    }else{
                        $datas['giveid'] = $arr['giveid'];
                        $datas['pay_balance'] = $zsgive['cz_money'];
                    }
                    $CardUpdateAli->allowField(true)->save($datas);

                    $arrs = ['code' => 0, 'message' => '成功'];
                } else {
                    $arrs = ['code' => $content['alipay_marketing_card_update_response']['code'], 'message' => $content['alipay_marketing_card_update_response']['msg']];
                }
            } else {
                $arrs = ['code' => 9001, 'message' => '更新失败'];
            }
        } else {
            $arrs = ['code' => 9002, 'message' => '访问方式不正确'];
        }
        return json($arrs);
    }

    //核销余额
    public function getcardupdateali(){
        if (Request()->isAjax()) {
            $arr = request()->param();
            $CardGetUserAli = new CardUserGetAli();
//            return json($arr);
            $res = $CardGetUserAli->where(['id' => $arr['id']])->setDec('balance', $arr['add_balance']);
            if ($res) {
                $user = $CardGetUserAli->where(['id' => $arr['id']])->field('template_id,user_id,mid,code,bonus,balance,open_date,valid_date')->find();
//                return json($user);
                //初始化
                $datas['merchid'] = $user['mid'];
                $User = new Merchant();
                $Agent = new Agent();
                $users = $User->where(array('id' => $datas['merchid']))->find();
                $agent = $Agent->where(array('id' => $users['agent']))->find();
                $options = array(
                    'appid' => $agent['ali_app_id'], // 填写高级调用功能的app id
                    'rsaPrivateKey' => $agent['ali_app_key'],
                );
                $aliObj = new Alipayobj($options);
                $data['app_id'] = $agent['ali_app_id'];
                $data['method'] = "alipay.marketing.card.update";
                $data['charset'] = "UTF-8";
                $data['sign_type'] = "RSA2";
                $data['timestamp'] = date('Y-m-d H:i:s');
                $data['version'] = "1.0";
                $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
                $data['app_auth_token'] = $users['ali_merid'];
                $data['biz_content'] = json_encode(array(
                    'target_card_no' => $user['code'],
                    'target_card_no_type' => 'BIZ_CARD',
                    'occur_time' => date('Y-m-d H:i:s'),
                    'card_info' => array(
                        'open_date' => $user['open_date'],
                        'valid_date' => $user['valid_date'],
                        'balance' => $user['balance'],
                    ),
                    'notify_messages' => array(
                        array(
                            'message_type' => 'BALANCE_UPDATE',
                            'ext_info' => '余额变动300'.$arr['add_balance'],
                        ),
                    ),
                ));
                $signContent = $aliObj->rsaSign($data, $signType = "RSA2");
                $data['sign'] = $signContent;
                $sj = $aliObj->scanpay($data);
                $content = json_decode(iconv("GB2312", "UTF-8//IGNORE", $sj), true);
                if ($content['alipay_marketing_card_update_response']['code'] = 10000) {
                    //记录
                    $CardUpdateAli = new CardUserUpdateAli();
                    $datas['top_mid']=Session::get('login_top_mid');
                    $datas['mid']=$user['mid'];
                    $datas['user_id']=$user['user_id'];
                    $datas['code']=$user['code'];
                    $datas['con_username']= $arr['username'];
                    $datas['template_id']=$user['template_id'];
                    $datas['del_balance']=$arr['add_balance'];
                    $datas['record_balance']='余额核销';
                    $datas['hx_fs']=4;
                    $datas['source']=1;
                    $datas['create_time']=time();
                    $datas['reason']=3;
                    $datas['type'] = $arr['type'];
                    $datas['notify_optional'] = json_encode($content,JSON_UNESCAPED_UNICODE);
                    $CardUpdateAli->allowField(true)->save($datas);
                    $arrs = ['code'=>0,'message'=>'成功'];
                }else{
                    $arrs = ['code'=>$content['alipay_marketing_card_update_response']['code'],'message'=>$content['alipay_marketing_card_update_response']['msg']];
                }
            }else{
                $arrs = ['code'=>9001,'message'=>'更新失败'];
            }
        }else{
            $arrs = ['code'=>9002,'message'=>'访问方式不正确'];
        }
        return json($arrs);
    }



    //领卡会员
    public function getlistali($template_id){
        $p_data = request()->get();
        unset($p_data['page']);
        unset($p_data['template_id']);
        $map = [];
        if ($p_data) {
            if ($p_data['code']) {
                $map['code|phone|old_code'] = array('like', '%' . trim($p_data['code']) . '%');
            } else {
                $p_data['code'] = '';
            }
            //积分筛选
            if ($p_data['bonus_scr']){
                $ord['bonus'] = $p_data['bonus_scr'] ==1 ? 'desc' : 'asc';
            }else{
                $p_data['bonus_scr'] = '';

            }
            //余额筛选
            if ($p_data['balance_scr']){
                $ord['balance'] = $p_data['balance_scr'] ==1 ? 'desc' : 'asc';
            }else{
                $p_data['balance_scr'] = '';
            }
            //时间筛选
            if ($p_data['get_scr']){
                $ord['create_time'] = $p_data['get_scr'] ==1 ? 'asc' : 'desc';
            }else{
                $p_data['get_scr'] = '';
            }
            $ord['id'] = 'desc';
        } else {
            $p_data['code'] = '';
            $p_data['bonus_scr'] = '';
            $p_data['balance_scr'] = '';
            $p_data['get_scr'] = '';
            $ord['id'] = 'asc';
        }
        $map['template_id'] = $template_id;
        $CardUserGetAli = new CardUserGetAli();
        $list = $CardUserGetAli->where($map)->paginate('20',false,['query' => request()->param()]);
        $card['template_id'] = $template_id;
        $card['type'] = 0;
        $user = Session::get('user');
        $this->assign('user',$user);
        $this->assign('czgive',[]);
        $this->assign('p_data',$p_data);
        $this->assign('card',$card);
        $this->assign('list',$list);
        return $this->fetch();
    }

    //领取会员修改
    public function edituserinfoali(){
        $CardUserGetAli = new CardUserGetAli();
        if (Request()->isPost()){
            $id = request()->param('id');
            $arr = request()->post();
            $data = $arr;
            $res = $CardUserGetAli->save($data,['id'=>$id]);
            if ($res){
                $this->success('修改成功',url('alicards/edituserinfoali',['id'=>$id]));
            }else{
                $this->error('修改失败',url('alicards/edituserinfoali',['id'=>$id]));
            }
        }else{
            $id = request()->param('id');
            $map['id'] =$id;
            $user = $CardUserGetAli->where($map)->find();
            $this->assign('user',$user);
            return $this->fetch();
        }
    }

    //会员卡删除
    public function delcardsali(){
        $CardUserGetAli = new CardUserGetAli();
        $arr = request()->param();
        //初始化
        $datas['merchid'] = $this->get_mid($arr['template_id']);
        $map['code'] = $arr['code'];
        $map['top_mid'] = Session::get('login_top_mid');
        $user = $CardUserGetAli->where($map)->field('id,template_id,external_card_no');
        $User = new Merchant();
        $Agent = new Agent();
        $users = $User->where(array('id' => $datas['merchid']))->find();
        $agent = $Agent->where(array('id' => $users['agent']))->find();
        $options = array(
            'appid' => $agent['ali_app_id'], // 填写高级调用功能的app id
            'rsaPrivateKey' => $agent['ali_app_key'],
        );
        $aliObj = new Alipayobj($options);
        $data['app_id'] = $agent['ali_app_id'];
        $data['method'] = "alipay.marketing.card.activateurl.apply";
        $data['charset'] = "UTF-8";
        $data['sign_type'] = "RSA2";
        $data['timestamp'] = date('Y-m-d H:i:s');
        $data['version'] = "1.0";
        $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
        $data['app_auth_token'] = $users['ali_merid'];
        $data['biz_content'] = json_encode(array(
            'out_serial_no' => $user['template_id'],
            'target_card_no'=> $user['external_card_no'],
            'target_card_no_type' => 'BIZ_CARD',
            'reason_code'=>'CANCEL',
        ));
        $signContent = $aliObj->rsaSign($data, $signType = "RSA2");
        $data['sign'] = $signContent;
        $sj = $aliObj->scanpay($data);
        $content = json_decode(iconv("GB2312", "UTF-8//IGNORE", $sj), true);
        if ($content['alipay_marketing_card_delete_response']['code'] == 10000){
            $datar['statu'] = 2;
            $CardUserGetAli->save($datar,$map);
        }
        return json($content);
    }

    //领卡二维码
    public function qrcodelistali($template_id){
        $CardLink = new CardLink();
        $map['template_id'] = $template_id;
        $map['card_type'] = 'OUT_MEMBER_CARD';
        $card['template_id'] = $template_id;
        $list = $CardLink->where($map)->select();
        $this->assign('list',$list);
        $this->assign('card',$card);
        return $this->fetch();
    }

    //添加二维码
    public function qrcodeaddali($template_id){
        if ($template_id){
            $request = Request::instance();
            $arr = request()->post();
            $CardLink = new CardLink();
            //初始化
            $datas['merchid'] = $this->get_mid($template_id);
            $User = new Merchant();
            $Agent = new Agent();
            $users = $User->where(array('id' => $datas['merchid']))->find();
            $agent = $Agent->where(array('id' => $users['agent']))->find();
            $options = array(
                'appid' => $agent['ali_app_id'], // 填写高级调用功能的app id
                'rsaPrivateKey' => $agent['ali_app_key'],
            );
            $aliObj = new Alipayobj($options);
            $data['app_id'] = $agent['ali_app_id'];
            $data['method'] = "alipay.marketing.card.activateurl.apply";
            $data['charset'] = "UTF-8";
            $data['sign_type'] = "RSA2";
            $data['timestamp'] = date('Y-m-d H:i:s');
            $data['version'] = "1.0";
            $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
            $data['app_auth_token'] = $users['ali_merid'];
            $data['biz_content'] = json_encode(array(
                'template_id' => $template_id,
                "callback" => $request->domain() .'/mobile.php/cardaliget/cardget',
            ));
            $signContent = $aliObj->rsaSign($data, $signType = "RSA2");
            $data['sign'] = $signContent;
            $sj = $aliObj->scanpay($data);
            $content = json_decode(iconv("GB2312", "UTF-8//IGNORE", $sj), true);
//            return json($content);
            if ($content['alipay_marketing_card_activateurl_apply_response']['code'] == 10000) {
                $datar['getcard_url'] = urldecode($content['alipay_marketing_card_activateurl_apply_response']['apply_card_url']);
                $datar['top_mid'] = Session::get('login_top_mid');
                $datar['mid'] = $this->get_mid($template_id);
                $datar['card_type'] = 'OUT_MEMBER_CARD';
                $datar['template_id'] = $template_id;
                $datar['link_info'] = json_encode($content,JSON_UNESCAPED_UNICODE);
                $datar['create_time'] = time();
                $res = $CardLink->save($datar);
                if ($res){
                    $params['code'] = 0;
                    $params['data']['url'] = urldecode($content['alipay_marketing_card_activateurl_apply_response']['apply_card_url']);
                }else{
                    $params['code'] = 2;
                    $params['message'] = "数据修改失败";
                }
            } else {
                $params['code'] = $content['alipay_marketing_card_activateurl_apply_response']['code'];
                $params['data']['msg'] = $content['alipay_marketing_card_activateurl_apply_response']['msg'];;
            }
            return json($params);

        }
    }

    //二维码删除
    public function qrcodedelali(){
        $arr = request()->param();
        $CardLink = new CardLink();
        $data['top_mid'] = Session::get('login_top_mid');
        $data['mid'] = $this->get_mid($arr['template_id']);
        $data['template_id'] = $arr['template_id'];
        $data['id'] = $arr['id'];
        $res = $CardLink->where($data)->delete();
        if ($res){
            $this->success('删除成功');
        }else{
            $this->error('删除失败');
        }
    }

    //等级管理
    public function ranklistali(){
        $Cardrank = new CardRank();
        $map['template_id'] = request()->param('template_id');
        $list = $Cardrank->where($map)->select();
        $this->assign('list',$list);
        $this->assign('card',$map);
        return $this->fetch();
    }

    //等级添加
    public function rankaddali(){
        $CardRank = new CardRank();
        $template_id = request()->param('template_id');
        if (Request()->isPost()){
            $data = request()->post();
            $data['template_id'] = $template_id;
            $data['create_time'] = time();
            $conten = $CardRank->allowField(true)->save($data);
            if($conten !== false){
                $this->success('修改成功！',url('alicards/ranklistali',['template_id'=>$template_id]),'',10);
            }else{
                $this->error('新增失败',url('alicards/ranklistali',['template_id'=>$template_id]));
            }
        }else {
            $map['template_id'] = $template_id;
            $this->assign('card', $map);
            return $this->fetch();
        }
    }

    //等级修改
    public function rankeditali(){
        $CardRank = new CardRank();
        $template_id = request()->param('template_id');
        $id = request()->param('id');
        if (Request()->isPost()){
            $data = request()->post();
            $data['update_time'] = time();
            $maps['template_id'] = $template_id;
            $maps['id'] = $id;
            $conten = $CardRank->allowField(true)->save($data,$maps);
            if($conten !== false){
                $this->success('修改成功！',url('alicards/ranklistali',['template_id'=>$template_id]),'',10);
            }else{
                $this->error('新增失败',url('alicards/ranklistali',['template_id'=>$template_id]));
            }
        }else {

            $map['template_id'] = $template_id;
            $info = $CardRank->where('id',$id)->find();
            $this->assign('card', $map);
            $this->assign('info',$info);
            return $this->fetch();
        }
    }

    //等级删除
    public function rankdelali($id,$template_id){
        $CardRank = new CardRank();
        $res = $CardRank->where('id',$id)->delete();
        if ($res){
            $this->success('删除成功！',url('alicards/ranklistali',['template_id'=>$template_id]));
        }else{
            $this->error('删除失败!',url('alicards/ranklistali',['template_id'=>$template_id]));
        }
    }


    //会员卡会员中心管理
    public function usercenterali($template_id){
        $CardMemberAli = new CardMemberAli();
        if (Request()->isPost()){
            $arr = request()->post();
            $res = $CardMemberAli->save($arr,['template_id'=>$template_id]);
            if ($res == false){
                $this->error('修改失败！',url('alicards/usercenter',['template_id'=>$template_id]));
            }else{
                $this->success('修改成功！',url('alicards/usercenter',['template_id'=>$template_id]));
            }
        }else{
            $info = $CardMemberAli->where(['template_id'=>$template_id])->find();
            $this->assign('card',$info);
            return $this->fetch();
        }
    }

    //积分设置
    public function bonussetali()
    {
        $template_id = request()->param('template_id');
        if (Request()->isPost()){
            $arr = request()->post();
            $CardBonusRule = new CardBonusRule();
            $only = $CardBonusRule->where(['template_id'=>$template_id,'type'=>$arr['type']])->find();
            if (!$only){
                $data = $arr;
                $data['template_id'] = $template_id;
                $data['begin_time'] = strtotime($arr['begin_time']);
                $data['end_time'] = strtotime($arr['end_time']);
                $data['top_mid'] = Session::get('login_top_mid');
                $data['creattime'] = time();
                $res = $CardBonusRule->allowField(true)->save($data);
                if ($res){
                    $this->success('设置成功',url('alicards/bonussetali',['template_id'=>$template_id]));
                }else{
                    $this->error('设置失败',url('alicards/bonussetali',['template_id'=>$template_id]));
                }
            }else{
                $this->error('已设置过该类规则',url('alicards/bonussetali',['template_id'=>$template_id]));
            }
        }else{
            $CardBonusRule = new CardBonusRule();
            $rulelist = $CardBonusRule->where(['template_id'=>$template_id])->select();
            $card['template_id'] = $template_id;
            $this->assign('rulelist',$rulelist);
            $this->assign('card',$card);
            return $this->fetch();
        }
    }

    //储值管理
    public function storageglali(){
        $request = request();
        $CardUserUpdate = new CardUserUpdateAli();
        $template_id = $request->param('template_id');
        //聚合统计
        $payblance = $CardUserUpdate->where('template_id',$template_id)->sum('pay_balance');              //实际支付总额
        $sume['cztotal'] = $CardUserUpdate->where('template_id',$template_id)->sum('add_balance');       //卡面总额
        $sume['hxtotal'] = $CardUserUpdate->where('template_id',$template_id)->sum('del_balance');       //核销总额
        $sume['czthan'] = $sume['cztotal']-$sume['hxtotal'];                                                //余额
        $sume['czprofit'] =  abs((int)$sume['cztotal'] - (int)$payblance);                                                    //充值总额
        //搜索
        $p_data = $request->get();
        if (!isset($p_data['mid'])){
            $p_data['mid']='';
        }
        unset($p_data['page']);
        if ($p_data) {
            if ($p_data['mid'] != '') {
                switch ($p_data['type']) {
                    //统计当日
                    case '1':
                        $map['mid'] = array('like', '%' . trim($p_data['mid']) . '%');
                        break;
                    //储值
                    case '3':
                        $mapcz['mid'] = array('like', '%' . trim($p_data['mid']) . '%');
                        break;
                    //核销
                    case '4':
                        $maphx['mid'] = array('like', '%' . trim($p_data['mid']) . '%');
                        break;
                }
            }
        }else{
            $p_data['mid'] = '';
            $p_data['type'] = '';
        }
        //当天列表
        $day = strtotime(date('Y-m-d'));
        $day2 =  $day + 86399;
        $map['template_id'] = $template_id;
        $map['create_time'] = ['between', '' .$day. ',' .$day2.''];
        $daylist = $CardUserUpdate->where($map)->select();
        //充值规则
        $CardCzgive = new CardCzgive();
        $mazs['template_id'] = $template_id;
        $givelist = $CardCzgive->where($mazs)->select();
        //充值列表
        $mapcz['template_id'] = $template_id;
        $mapcz['add_balance'] = ['neq',0];
        $czlist = $CardUserUpdate->where($mapcz)->order('id desc')->paginate('20',false,['query' => request()->param()]);
        //核销列表
        $maphx['template_id'] = $template_id;
        $maphx['del_balance'] = ['neq',0];
        $hxlist = $CardUserUpdate->where($maphx)->order('id desc')->paginate('20',false,['query' => request()->param()]);
        //输出
        //门店
        $Merchant = new Merchant();
//        $mab['id'] = ['in',$this->get_mer_mid()];
//        $mach = $Merchant->where($mab)->select();
        $mach = [];
        $this->assign('p_data',$p_data);
        $this->assign('mach',$mach);
        $this->assign('daylist',$daylist);          //当天
        $this->assign('sume',$sume);                //聚合
        $this->assign('givelist',$givelist);        //规则
        $this->assign('card',$map);                 //基础
        $this->assign('czlist',$czlist);            //充值
        $this->assign('hxlist',$hxlist);            //核销
        return $this->fetch();
    }

    //会员卡开卡填写信息
    //必选字段
    /*
     * 表单必填字段配置，common_fields属性定义一个表单字段数组，字段有效值如下列表所示：
        OPEN_FORM_FIELD_MOBILE -- 手机号
        OPEN_FORM_FIELD_GENDER -- 性别
        OPEN_FORM_FIELD_NAME -- 姓名
        OPEN_FORM_FIELD_BIRTHDAY -- 生日（不含年份，如：01-01）
        OPEN_FORM_FIELD_BIRTHDAY_WITH_YEAR -- 生日（含年份，如：1988-01-01）
        OPEN_FORM_FIELD_IDCARD -- 身份证
        OPEN_FORM_FIELD_CERT_TYPE -- 证件类型
        OPEN_FORM_FIELD_CERT_NO -- 证件号
        OPEN_FORM_FIELD_EMAIL -- 邮箱
        OPEN_FORM_FIELD_ADDRESS -- 地址
        OPEN_FORM_FIELD_CITY -- 城市
        OPEN_FORM_FIELD_IS_STUDENT -- 是否学生认证
        OPEN_FORM_FIELD_MEMBER_GRADE -- 会员等级

        注：
        1. 会员等级、是否学生认证字段，如果获取不到该项数据时，表单页面不做展示。
        2. 身份证字段和证件号、证件类型字段不可同时配置。
        3. 如果身份证字段不能满足业务需求，可通过配置证件类型+证件号字段来获取其他证件类型的支持，目前支持的证件类型有：身份证、护照、港澳居民通行证、台湾居民通行证
                 * */
    public function cardopenInfo($template_id)
    {
        if (Request()->isPost()) {
            $arr = request()->post();
//            return json($arr);
            //获取mid
            $datas['merchid'] = $this->get_mid($template_id);

            //初始化
            $User = new Merchant();
            $Agent = new Agent();
            $users = $User->where(array('id' => $datas['merchid']))->find();
            $agent = $Agent->where(array('id' => $users['agent']))->find();
            $options = array(
                'appid' => $agent['ali_app_id'], // 填写高级调用功能的app id
                'rsaPrivateKey' => $agent['ali_app_key'],
            );
            $aliObj = new Alipayobj($options);

            //修改参数
            $data['app_id'] = $agent['ali_app_id'];
            $data['method'] = "alipay.marketing.card.formtemplate.set";
            $data['charset'] = "UTF-8";
            $data['sign_type'] = "RSA2";
            $data['timestamp'] = date('Y-m-d H:i:s');
            $data['version'] = "1.0";
            $data['app_auth_token'] = $users['ali_merid'];
            $biz_content['template_id'] = $template_id;
            if (isset($arr['is_btian'])){
                $biz_content['fields']['required']['common_fields'] = $arr['is_btian'];
            }
            if(isset($arr['is_xtian'])){
                $biz_content['fields']['optional']['common_fields'] = $arr['is_xtian'];
            }
            $data['biz_content'] = json_encode(
                $biz_content
//                array(
//                'template_id' => $template_id,
//                'fields' => array(
//                    'required' => array(
//                        'common_fields' => $arr['is_btian']
//                    ),
//                    'optional' => array(
//                        'common_fields' => $arr['is_xtian']
//                    )
//                ),
//            )
            );
            $signContent = $aliObj->rsaSign($data, $signType = "RSA2");
            $data['sign'] = $signContent;
//            var_dump($data,JSON_UNESCAPED_UNICODE);
            //修改结果
            $sj = $aliObj->scanpay($data);
            $content = json_decode(iconv("GB2312", "UTF-8//IGNORE", $sj), true);
//            return json($content);
            //结果判断
            if ($content['alipay_marketing_card_formtemplate_set_response']['code'] = 10000) {
                $datas['activatef'] = json_encode($data['biz_content'], JSON_UNESCAPED_UNICODE);
                $datas['update_time'] = time();
                $CardMemberAli = new CardMemberAli();
                $res = $CardMemberAli->save($datas, ['template_id' => $template_id]);
                if ($res) {
                    $params['code'] = 0;
                    $params['message'] = "设置成功";
                } else {
                    $params['code'] = 2;
                    $params['message'] = "数据修改失败";
                }
            } else {
                $params['code'] = $content['alipay_marketing_card_formtemplate_set_response']['code'];
                $params['message'] = "设置失败";
            }
            return json($params);
        }else{
            $CardMemberAli = new CardMemberAli();
            $card['template_id'] = $template_id;
            $info = $CardMemberAli->where($card)->find();
            $info['activatef'] = json_decode($info['activatef'],true);
            $this->assign('card',$card);
            $this->assign('activate',json_encode($info['activatef'],JSON_UNESCAPED_UNICODE));
            return $this->fetch();
        }
    }


    //获取会员卡领卡投放链接
    public function card_activateurl($template_id)
    {
        //初始化
        $datas['merchid'] = $this->get_mid($template_id);
        $User = new Merchant();
        $Agent = new Agent();
        $users = $User->where(array('id' => $datas['merchid']))->find();
        $agent = $Agent->where(array('id' => $users['agent']))->find();
        $options = array(
            'appid' => $agent['ali_app_id'], // 填写高级调用功能的app id
            'rsaPrivateKey' => $agent['ali_app_key'],
        );
        $aliObj = new Alipayobj($options);
        $data['app_id'] = $agent['ali_app_id'];
        $data['method'] = "alipay.marketing.card.activateurl.apply";
        $data['charset'] = "UTF-8";
        $data['sign_type'] = "RSA2";
        $data['timestamp'] = date('Y-m-d H:i:s');
        $data['version'] = "1.0";
        $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
        $data['app_auth_token'] = $users['ali_merid'];
        $data['biz_content'] = json_encode(array(
            'template_id' => $template_id,
            "callback" => $http_type . $_SERVER['HTTP_HOST'] . url('Alicards/opencardlq'),
        ));
        $signContent = $aliObj->rsaSign($data, $signType = "RSA2");
        $data['sign'] = $signContent;
        return json($data);
        $sj = $aliObj->scanpay($data);
        $content = json_decode(iconv("GB2312", "UTF-8//IGNORE", $sj), true);
        if ($content['alipay_marketing_card_activateurl_apply_response']['code'] == 10000) {
            $CardMemberAli = new CardMemberAli();
            $datas['apply_card_url'] = urldecode($content['alipay_marketing_card_activateurl_apply_response']['apply_card_url']);
            $res = $CardMemberAli->save($datas,['template_id'=>$template_id]);
            if ($res){
                $params['code'] = 0;
                $params['data']['url'] = urldecode($content['alipay_marketing_card_activateurl_apply_response']['apply_card_url']);
            }else{
                $params['code'] = 2;
                $params['message'] = "数据修改失败";
            }
        } else {
            $params['code'] = $content['alipay_marketing_card_activateurl_apply_response']['code'];
            $params['data']['msg'] = $content['alipay_marketing_card_activateurl_apply_response']['msg'];;
        }

        return json($params);


    }

    //获取mid 通过tempalte_id
    private function get_mid($template_id){
        //获取mid
        $CardMemberAli = new CardMemberAli();
        $merchid = $CardMemberAli->where(array('template_id'=>$template_id))->value('mid');
        return $merchid;
    }

    //配置
//    private function optin($mid){
//
//        return $agent;
//    }


}